package com.squirrels.server.service;

import com.squirrels.server.common.constant.UserConstant;
import com.squirrels.server.message.Login;
import com.squirrels.server.message.UserData;
import dev.morphia.Datastore;
import dev.morphia.UpdateOptions;
import dev.morphia.aggregation.stages.Stage;
import dev.morphia.query.MorphiaCursor;
import dev.morphia.query.Query;
import dev.morphia.query.filters.Filters;

/**
 * 创建者: FlyingSquirrels
 * 创建时间: 2024/8/1 11:54
 * 描述: 用户服务
 */
public class UserService {

    private static UserService userService;
    private static Datastore datastore;

    public static synchronized UserService operation(Datastore datastore){
        if (null == UserService.userService) {
            UserService.userService = new UserService();
            UserService.datastore = datastore;
        }
        return UserService.userService;
    }

    public static synchronized UserService operation(){
        return UserService.userService;
    }

    // 登录
    public Login login(Login login){
        Query<Login> logins = datastore.find(Login.class);
        MorphiaCursor<Login> userIter = logins.filter(Filters.eq("username", login.getUsername()),Filters.eq("password",login.getPassword()))
                .iterator();
        if (null == userIter || !userIter.hasNext()) {
            return null;
        }
        Login next = userIter.next();
        return next;
    }

    // 根据名称查找用户是否存在
    public boolean searchByName(String name){
        Login login = getByName(name);
        if (login == null){
            return false;
        }else{
            return true;
        }
    }

    // 根据名称查找用户是否存在
    public Login getByName(String name){
        Query<Login> logins = datastore.find(Login.class);
        MorphiaCursor<Login> userIter = logins.filter(Filters.eq("username", name)).iterator();
        if (userIter.hasNext() == true) {
            return userIter.next();
        }
        return null;
    }

    // 重置密码
    public boolean resetPassword(String username, String password) {
        Login login = getByName(username);
        if (null == login){
            return false;
        }
        if (login.getPassword().equals(password)){
            return true;
        }
        login.setPassword(password);
        datastore.replace(login);
        return true;
    }

    // 增加用户金额
    public void addGlod(String uid, long source) {
        Query<UserData> logins = datastore.find(UserData.class);
        MorphiaCursor<UserData> userIter = logins.filter(Filters.eq("userId", uid))
                .iterator();
        if(userIter.hasNext()){
            UserData data= userIter.next();
            data.setGold(source);
            datastore.replace(data);
        }else{
            return;
        }
    }
}
